package com.uni.service.impl;

import com.uni.dao.UserMapper;
import com.uni.pojo.User;
import com.uni.service.UserService;
import com.uni.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    public List<User> findAll() {
        return userMapper.selectAllUser();
    }

    @Override
    public User login(User user) {
        // 首先在Redis获取用户
        String key = String.format("user:%s", user.getEmail());
        User cacheUser = (User)redisTemplate.opsForValue().get(key);
        if(cacheUser == null || !cacheUser.getPassword().equals(user.getPassword())){
            System.out.println("[fail]" + TimeUtil.getCurTime() + "未从Redis缓存中读取到用户[" + user.getEmail() + "]");
        } else {
            System.out.println("[success]"+TimeUtil.getCurTime() + "读取Redis缓存成功!");
            return cacheUser;
        }
        // 缓存找不到则从MySQL里查找
        return userMapper.selectByEmailAndPassword(user);
    }

    @Override
    public int register(User user) {
        int i = userMapper.insert(user);
        if(i > 0) {
            // 记录用户信息
            String key = String.format("user:%s", user.getEmail());
            // 存入Redis缓存
            redisTemplate.opsForValue().set(key, user);
            System.out.println("[success]" + TimeUtil.getCurTime() + "用户存入Redis缓存成功!");
        }
        return i;
    }
}
